from flask import Flask, request
import contextlib
import OpenSSL
import base64

app = Flask(__name__)

@app.route('/')
def hello_world():
    ###################################################
    '''
    with contextlib.closing(open('190.pem')) as f:
        private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, f.read())
    # 私钥加密后进行Base64转码
    sing = base64.encodestring(OpenSSL.crypto.sign(private_key, val, 'sha1'))
    print(str(sing))

    with contextlib.closing(open('190.pem')) as f:
        certificate = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
        public_key = certificate.get_pubkey()
    print(OpenSSL.crypto.verify(certificate, base64.decodestring(sing), val, 'sha1'))
    '''
    ############################################################
    return 'Hello World'


@app.route("/demo", methods=["POST"])
def demo():
    processFlag = request.args.get("processFlag")  # 处理结果 0：成功 1：失败
    txnType = request.args.get("txnType")  # 交易类型
    orgTxnType = request.args.get("orgTxnType")  # 原始交易类
    amt = request.args.get("amt")  # 交易金额
    externalTraceNo = request.args.get("externalTraceNo")  # 外部跟踪编号
    orgExternalTraceNo = request.args.get("orgExternalTraceNo")  # 原始外部跟踪号
    terminalOperId = request.args.get("terminalOperId")  # 操作员编号
    terminalId = request.args.get("terminalId")  # 终端编号
    authCode = request.args.get("authCode")  # 授权码
    RRN = request.args.get("RRN")  # 系统参考号
    txnTime = request.args.get("txnTime")  # 交易时间
    shortPAN = request.args.get("shortPAN")  # 缩略卡号
    responseCode = request.args.get("responseCode")  # 交易返回码
    responseMessage = request.args.get("responseMessage")  # 交易返回信息
    cardType = request.args.get("cardType")  # 卡类型
    issuerId = request.args.get("issuerId")  # 发卡机构
    issuerIdView = request.args.get("issuerIdView")  # 发卡机构名称
    signature = request.args.get("signature")   # "Wte6KhNRzMNm1kU7DKcGX09LrnuWl08NH0UFKj+Kg+j7ZfksWHPbARjS6Q3ppLMNsP1lIonF144b7tScqbOoDO/Ep7K9mtRmeE+RWx+UjObmAaTmQmCQ93C7k6gRklIOvYd95VeXtwOsf9tbYdAo8bZjKPKaBbjc/oHHKgDuNR4="
    val = processFlag + txnType + amt + externalTraceNo + terminalOperId + authCode + RRN + txnTime + shortPAN + responseCode + cardType + issuerId
    val = "orderId=120906100160reqTime=20120906110617"

    with contextlib.closing(open('certs/mgw.pem')) as f:
        certificate = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
    result = OpenSSL.crypto.verify(certificate, base64.decodestring(str.encode(signature)), val, 'sha1')
    if result is None:
        return "ok"
    else:
        return "no"


if __name__ == '__main__':
    app.run()


